app.register.controller('CarOwnerCtrl', function($scope, $rootScope,
		CarOwnerSer, AppUtil, $http, $q,$location,$routeParams) {
	
	loadFlag($routeParams.id,$scope);
	
	
	var myDate = new Date(); 
    function addzero(v) {if (v < 10) return '0' + v;return v.toString();}
	var today = myDate.getFullYear().toString() + '-'+addzero(myDate.getMonth() + 1) + '-' +addzero(myDate.getDate());
	$("#rocreatedate1").val(today);
	$("#rocreatedate2").val(today);
	
	$scope.pagination = {
			currentPage :1,
			itemsPerPage :10
	};

	$scope.SearchData = function() {
		$scope.postData={};
		// 点击查询按钮时,恢复页码为1
		$scope.pagination.currentPage = 1
		// 表单查询参数
		LoadList();
	};
	
	// 加载数据方法
	var LoadList = function() {
		if ($scope.postData == undefined)
			$scope.postData = {};
		var params = AppUtil.Params(".form_params");
		params = $.extend({}, $scope.selected,params);
		params["brandname"] = angular.element('select[name=brand]').find("option:selected").text();
		params["seriesname"] = angular.element('select[name=series]').find("option:selected").text();
		params["modelname"] = angular.element('select[name=model]').find("option:selected").text();
		// 当有查询参数时,重置页数
		if (AppUtil.Length(params) > 0) {
			if($scope.entity_name != null){
				params['entity_name'] = $scope.entity_name;
			}
			$scope.postData.params = params;
		}
		// 筛选查询参数
		var search_opt = AppUtil.GetSearchOpt();
		if (search_opt.length > 0) {
			$scope.postData.search_opt = search_opt;
		}
		$scope.postData.page = $scope.pagination.currentPage;
		$scope.postData.size = $scope.pagination.itemsPerPage;
		if(!($("#rocreatedate1").val()&&$("#rocreatedate2").val())){
			alertMsg("提示", "开单日期为必填项");
			return;
		}
		if($("#mileage2").val()&&$("#mileage1").val()){
			if(parseFloat($("#mileage2").val())<parseFloat($("#mileage1").val())){ 
				alertMsg("提示", "结束里程不小于起始里程");
				return;
			}
		}
		
		
		// 加载数据
		CarOwnerSer.list($scope.postData).success(function(response) {
			AppUtil.remove_loading();
			$scope.pagination.totalItems = response.total;
			$scope.costReports = response.data.data;
			$scope.costSum = response.data.sum;
			setTimeout(check_table_tr,500);
		});
	}
	
	// 配置分页监听
	$scope.$watch('pagination.refresh', LoadList);
	
	//加载车主下拉
	$("#owner_no").select2({  
	        language: "zh-CN",  
	        allowClear: true,  
	        width: "260px",  
	        height:"25px",  
	        placeholder: "",  
	        ajax: {  
	            url: "cost/ownerList",  
	            dataType: 'json',  
	            delay: 500,  
	            data: function (params) {  
	                params.ec =$scope.currentEntity;
	                return {  
	                    name: params.term,    
	                    ec:params.ec  
	                };  
	            },  
	            cache: true,  
	            processResults: function (res, params) {  
	                if (res.success) {  
	                    var users = res.data;  
	                    var options = [];  
	                    for (var i = 0, len = users.length; i < len; i++) {
	                        var option = {  
	                            "id": users[i]["owner_no"] + "-" + users[i]["entity_code"],  
	                            "text": ( "["+users[i]["owner_no"] + "]" + users[i]["owner_name"]+ "("+ users[i]["entity_name"] +")")  
	                        };  
	                        options.push(option);  
	                    }  
	                    return {  
	                        results: options
	                    };  
	                }  
	            },  
	            escapeMarkup: function (markup) {  
	                return markup;  
	            },  
	            minimumInputLength: 1  
	        }  
	    });  
	 
	//加载品牌车系车型
	$http.get("common/brands").success(function(data) {
		$scope.brands = data;
		$scope.brandscopy = data;
	});
	
	$scope.LoadEntityBrands=function(entity){
		$scope.currentEntity= entity.entity_code;
		$rootScope.search_entity_name = entity.entity_name;
		$http.get("common/LoadEntityBrands?entity_code="+entity.entity_code).success(function(data) {
			$scope.ch_brand="";
			$rootScope.brands = data;
		});	
	};
	
	//清空门店
	$scope.clearGroupBrandEntity = function(){
		$scope.currentEntity= "";
		$rootScope.search_entity_name='';
		$scope.ch_brand = '';
		$("#owner_no").val(null).trigger("change");
		
		$scope.brands =$scope.brandscopy;
		$scope.pay_type = $scope.pay_type_copy;
		$scope.servicer = $scope.servicer_copy;
		$scope.mechanic = $scope.mechanic_copy;
		$scope.repair_type=$scope.repair_type_copy;
	}
	
	//门店监听
	$rootScope.$watch('search_entity_name', function(newValue,oldValue,scope){
		if(newValue==''){
			$scope.clearGroupBrandEntity();
		}else{
			$("#owner_no").val(null).trigger("change");
		}
	});
	
	$scope.setColor = function (isover) {
	    if (true == isover) {
	    	return {"background-color": '#FCF8E3'};
	    }else{
	    	return "";
	    }
	};	
	
	$scope.$watch('ch_brand', function(newValue,oldValue,scope){
		$scope.LoadSeries($scope.ch_brand,$scope.currentEntity);	
	});
	
	$scope.$watch('ch_serie', function(newValue,oldValue,scope){
		$scope.LoadModels($scope.ch_serie,$scope.currentEntity);	
	});
	//加载查询条件
	$http.get("carowner/dicts").success(function(data){
		$scope.province=data.data.area.province;
		$scope.city=data.data.area.city;
		$scope.country=data.data.area.country;
		
		$scope.city_sel=data.data.area.city;
		$scope.country_sel=data.data.area.country;
	});
	
	
	$scope.loadCity=function(name){
		$scope.city_sel=null;
		$scope.country_sel=null;
		$scope.City = '';
		var city=new Array();
		var group_code='';
		$.each($scope.province,function(i,o){
			if(o.status_desc==name){group_code=o.status_code;}
		})
		if(group_code!=''){
			$.each($scope.city,function(i,o){
				if(o.group_code==group_code){
					city.push(o);
				}
			})
			$scope.city_sel=city;
		}
	}
	
	
	$scope.loadCountry=function(name){
		$scope.country_sel=null;
		var country=new Array();
		var group_code='';
		$.each($scope.city,function(i,o){
			if(o.status_desc==name){group_code=o.status_code;}
		})
		if(group_code!=''){
			$.each($scope.country,function(i,o){
				if(o.group_code==group_code){
					country.push(o);
				}
			})
			$scope.country_sel=country;
		}
	}
	
	AppUtil.LoadGroups();
	// 导出
	$scope.ExportData = function() {
		AppUtil.ExportData($scope.postData);
	};
	
    $scope.formatStr = function(input){
		var returnStr = "";
		if(input == undefined){
			return;
		}
		var itemArr = input.split(";");
		for (var i = 0; i < itemArr.length; i++) {
			var temp = itemArr[i].split(":");
			if(temp.length>1){
				returnStr += temp[1];
			}else{
				returnStr += itemArr[i];
			}
		}
	    return returnStr;
	}
});
app.register.service('CarOwnerSer', function($http, AppUtil) {

	// 查询数据
	this.list = function(postData) {
		AppUtil.loading();
		postData.start = (postData.page - 1 < 0 ? 0 : postData.page - 1)
				* postData.size;
		return $http.post('carowner/list', postData).error(function() {
			alertMsg("提示", "系统出错,请稍后重试.");
			AppUtil.remove_loading();
		});
	};
	
	
});
